package aggregation

import (
	"encoding/json"
	"gluenet/pkg/apis"
	"strings"
	"sync"
	"time"
)

func inGroupMetric(metric string) (string, bool) {
	var metrics = map[string]string{
		"container_cpu_used_cores":    "application_cpu_used_cores_total",
		"container_memory_used_bytes": "application_memory_used_bytes_total",
	}

	label, ok := metrics[metric]

	return label, ok
}

func gluenetsApplicationMetrics(c *apis.StorageContext) {
	var data = make(map[string]map[string]interface{})
	c.MetricCache.Range(func(key, value interface{}) bool {
		keyi := strings.Split(key.(string), "|")
		if label, ok := inGroupMetric(keyi[1]); ok {
			keyi[3] = "*"
			keyi[1] = label
			nkey := strings.Join(keyi, "|")
			odata := value.(map[string]interface{})
			if _, ok := data[nkey]; !ok {
				data[nkey] = map[string]interface{}{
					"object":    odata["object"],
					"platform":  odata["platform"],
					"time":      time.Now().Unix(),
					"value":     odata["value"],
					"label":     label,
					"guid":      odata["guid"],
					"container": "*",
				}
			} else {
				data[nkey]["value"] = data[nkey]["value"].(float64) + odata["value"].(float64)
			}
		}
		return true
	})

	//c.Logger.Debugf("data %v ", data)

	for k, vd := range data {
		var sub *sync.Map
		subi, _ := c.MetricsSubscriber.LoadOrStore(k, &sync.Map{})
		sub = subi.(*sync.Map)

		bts, _ := json.Marshal(vd)
		str := string(bts)

		sub.Range(func(k, v interface{}) bool {
			mch := v.(chan string)
			mch <- str
			return true
		})

		c.MetricsSubscriberTotal.Range(func(k, v interface{}) bool {
			mch := v.(chan string)
			mch <- str
			return true
		})
	}
}
